#!/usr/bin/env python3

import argparse
import json
import os

RUST_TARGETS = [
    "aarch64-apple-ios",
    "aarch64-apple-ios-sim",
    "aarch64-linux-android",
    "armv7-linux-androideabi",
    "wasm32-unknown-emscripten",
]
LIB_NAME = "libwallet_core_rs.a"


def display_size(size_kb: int) -> str:
    if size_kb >= 10000:
        size_mb = float(size_kb) / 1024
        return f'{size_mb:.2f} MB'
    else:
        return f'{size_kb} KB'


def display_diff(diff_kb: int) -> str:
    if abs(diff_kb) >= 10000:
        diff_mb = float(diff_kb) / 1024
        return f'{diff_mb:+.2f} MB'
    else:
        return f'{diff_kb:+} KB'


def measure_rust(_args):
    result = {}

    for target in RUST_TARGETS:
        path = f'rust/target/{target}/release/{LIB_NAME}'
        file_stats = os.stat(path)
        file_size_kb = file_stats.st_size / 1024
        result[target] = int(file_size_kb)

    print(json.dumps(result))


def compare_sizes(args):
    def display_target(target: str, before_kb: int, current_kb: int):
        diff_kb = current_kb - before_kb
        if before_kb == current_kb:
            print(f'➡️ **{target}**: {display_size(before_kb)}')
        else:
            print(f'➡️ **{target}**:')
            print("```diff")
            print(f'- {display_size(before_kb)}')
            print(f'+ {display_size(current_kb)} \t {display_diff(diff_kb)}')
            print("```")

    current_json = json.load(open(args.current, 'r'))
    before_json = {}
    if os.path.isfile(args.before):
        before_json = json.load(open(args.before, 'r'))

    print("## Binary size comparison")
    print()
    for target, current_kb in current_json.items():
        before_kb = before_json.get(target, current_kb)
        display_target(target, before_kb, current_kb)
        print()


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="GitHub CI helper functions")
    subparsers = parser.add_subparsers()

    measure_parser = subparsers.add_parser('measure-rust', help="Measures Rust release binaries'")
    measure_parser.set_defaults(func=measure_rust)

    compare_parser = subparsers.add_parser('compare',
                                           help="Compares binary sizes. Takes 'before' and 'current' file names")
    compare_parser.add_argument('--before', type=str)
    compare_parser.add_argument('--current', type=str)
    compare_parser.set_defaults(func=compare_sizes)

    args = parser.parse_args()
    args.func(args)
